#!/bin/bash -e
#
# 40-maas-01-machine-resources - Download and run binary to collect machine details
#
# Copyright (C) 2021 Canonical
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# --- Start MAAS 1.0 script metadata ---
# name: 40-maas-01-machine-resources
# title: Download and run binary to collect machine details
# description: Download and run binary to collect machine details
# script_type: commissioning
# timeout: 60
# --- End MAAS 1.0 script metadata ---

resources_bin=$(mktemp)
[ "$SNAP_ARCH" ] && arch="$SNAP_ARCH" || arch="$(dpkg --print-architecture)"
wget "$MAAS_BASE_URL/MAAS/machine-resources/$arch" -O "$resources_bin" >&2
chmod +x "$resources_bin"

# MAAS_RESOURCES_FILE is owned by maas on deb-based MAAS controllers
file_owner=$(stat -c '%U' "$MAAS_RESOURCES_FILE")
[ "$file_owner" = "maas" ] && tee_cmd="sudo -n -u maas tee" || tee_cmd="tee"
"$resources_bin" | $tee_cmd "$MAAS_RESOURCES_FILE"

rm "$resources_bin"
